<template>
  <div id="myList" class="myList">
    <ul>
      <li v-for="item in list" :key="item.id">
        <el-popover placement="top">
          <p>确定删除吗？</p>
          <div style="text-align: right; margin: 10px 0 0">
            <el-button type="primary" size="small" @click="deleteCollect(item.id)">确定</el-button>
          </div>
          <i class="el-icon-close delete" slot="reference" v-show="isDelete"></i>
        </el-popover>
        <router-link :to="{ path: '/detail', query: {pet:JSON.stringify({id:item.id,fromPage:this.toPage})} }" @click.native="load">
          <img :src=item.url alt="" />
          <h2>{{item.name}}</h2>
          <h3>{{item.good_specific}}</h3>
          <p>
            <span>{{item.price}}元</span>
<!--            添加折扣价-->
            <span
                v-show="price !== item.price"
                class="del"
            >{{item.price}}元</span>
          </p>
        </router-link>
      </li>
      <li v-show="isMore && list.length>=1" id="more">
        <router-link :to="{ path: `/goods?categoryID=${categoryID}`, query: {categoryID:categoryID} }">
          浏览更多
          <i class="el-icon-d-arrow-right"></i>
        </router-link>
      </li>
    </ul>
  </div>
</template>
<script>
export default {
  name: "MyList",
  inject:['reload'],
  // list为父组件传过来的商品列表
  // isMore为是否显示“浏览更多”
  props: ["list", "isMore", "isDelete","categoryID"],
  data() {
    return {
      toPage:7
    };
  },
  computed: {
    // 通过list获取当前显示的商品的分类ID，用于“浏览更多”链接的参数
    categoryID: function() {
      let categoryID = [];
      if (this.list !== "") {
        for (let i = 0; i < this.list.length; i++) {
          const id = this.list[i].category_id;
          if (!categoryID.includes(id)) {
            categoryID.push(id);
          }
        }
      }
      return categoryID;
    }
  },
  watch:{
    $route:function (val){
      if (val.path === '/goods'){
        this.toPage = 8
      }else {
        this.toPage = 7
      }
      console.log(this.toPage)
    }
  },
  methods: {
    deleteCollect(product_id) {
      this.$axios
          .delete(`${this.$target}/cart/delete/${this.$store.getters.getUser.id}`)
          .then(res => {
            switch (res.data.status.toString()) {
              case "0":
                // 删除成功
                // 删除删除列表中的该商品信息
                for (let i = 0; i < this.list.length; i++) {
                  const temp = this.list[i];
                  if (temp.id === product_id) {
                    this.list.splice(i, 1);
                  }
                }
                // 提示删除成功信息
                this.notifySucceed(res.data.message);
                break;
              default:
                // 提示删除失败信息
                this.notifyError(res.data.message);
            }
          })
          .catch(err => {
            return Promise.reject(err);
          });
    },
    load(){
      this.reload();
    }
  }
};
</script>

<style scoped>
@import "../assets/less/myList.less";
</style>
